from flask import Flask, jsonify, request
import sys
import os
from decimal import Decimal

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from flask import Flask, jsonify, request, json
from flask_cors import CORS
from backend.database.db_connection import DatabaseConnection

app = Flask(__name__)
# 配置CORS，允许所有来源访问
CORS(app)

# 自定义JSON编码器，处理Decimal类型
class CustomJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            # 将Decimal转换为float
            return float(obj)
        return super(CustomJSONEncoder, self).default(obj)

# 设置自定义JSON编码器
app.json_encoder = CustomJSONEncoder

# 初始化数据库连接
db = DatabaseConnection()

# 测试数据库连接
@app.route('/api/test_db', methods=['GET'])
def test_db_connection():
    try:
        connection = db.connect()
        return jsonify({'status': 'success', 'message': '数据库连接成功'})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 注册API
@app.route('/api/auth/register', methods=['POST'])
def register():
    data = request.json
    
    if not data:
        return jsonify({'status': 'error', 'message': '请求数据为空'}), 400
    
    username = data.get('username')
    password = data.get('password')
    name = data.get('name')
    phone = data.get('phone')
    role = data.get('role')
    address = data.get('address', '')
    
    # 验证必要字段
    if not all([username, password, name, phone, role]):
        return jsonify({'status': 'error', 'message': '缺少必要的注册信息'}), 400
    
    try:
        from backend.database.user_db import UserDB
        from backend.models.user import User
        
        user_db = UserDB()
        
        # 检查用户名是否已存在
        existing_user = user_db.get_user_by_username(username)
        if existing_user:
            return jsonify({'status': 'error', 'message': '用户名已存在'}), 400
        
        # 创建新用户
        new_user = User(
            username=username,
            password=password,  # 注意：在实际应用中应该对密码进行加密
            name=name,
            phone=phone,
            role=role,
            address=address
        )
        
        # 添加用户到数据库
        user_id = user_db.add_user(new_user)
        
        return jsonify({
            'status': 'success',
            'user_id': user_id,
            'message': '注册成功'
        })
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 登录API
@app.route('/api/auth/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    role = data.get('role')
    
    if not username or not password or not role:
        return jsonify({'status': 'error', 'message': '缺少必要的登录信息'}), 400
    
    try:
        from backend.database.user_db import UserDB
        user_db = UserDB()
        
        # 验证用户身份
        user = user_db.authenticate_user(username, password, role)
        
        if user:
            return jsonify({
                'status': 'success',
                'user_id': user.user_id,
                'username': user.username,
                'role': user.role
            })
        else:
            return jsonify({'status': 'error', 'message': '用户名、密码或角色不正确'}), 401
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 用户相关API
@app.route('/api/users', methods=['GET'])
def get_users():
    from backend.database.user_db import UserDB
    user_db = UserDB()
    try:
        users = user_db.get_all_users()
        return jsonify([user.to_dict() for user in users])
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 菜品相关API
@app.route('/api/foods', methods=['GET'])
def get_foods():
    from backend.database.food_db import FoodDB
    food_db = FoodDB()
    try:
        foods = food_db.get_all_foods()
        return jsonify([food.to_dict() for food in foods])
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 订单相关API
@app.route('/api/orders', methods=['GET'])
def get_orders():
    from backend.database.order_db import OrderDB
    order_db = OrderDB()
    orders = order_db.get_all_orders()
    return jsonify([order.to_dict() for order in orders])

# 创建订单API
@app.route('/api/orders', methods=['POST'])
def create_order():
    data = request.json
    
    if not data:
        return jsonify({'status': 'error', 'message': '请求数据为空'}), 400
    
    try:
        from backend.database.order_db import OrderDB
        from backend.database.order_detail_db import OrderDetailDB
        from backend.models.order import Order
        
        # 创建订单
        order_db = OrderDB()
        order = Order(
            user_id=data.get('user_id'),
            order_status=data.get('order_status', '待支付'),
            total_amount=data.get('total_amount', 0)
        )
        
        # 添加订单并获取订单ID
        order_id = order_db.add_order(order)
        
        # 添加订单详情
        order_detail_db = OrderDetailDB()
        order_details = data.get('order_details', [])
        
        for detail in order_details:
            from backend.models.order_detail import OrderDetail
            order_detail = OrderDetail(
                order_id=order_id,
                food_id=detail.get('food_id'),
                quantity=detail.get('quantity'),
                unit_price=detail.get('unit_price'),
                subtotal=detail.get('subtotal')
            )
            order_detail_db.add_order_detail(order_detail)
        
        return jsonify({
            'status': 'success',
            'order_id': order_id,
            'message': '订单创建成功'
        })
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 获取用户详情API
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user_detail(user_id):
    try:
        from backend.database.user_db import UserDB
        user_db = UserDB()
        user = user_db.get_user_by_id(user_id)
        
        if user:
            # 不返回密码信息
            user_data = user.to_dict()
            user_data.pop('password', None)
            return jsonify(user_data)
        else:
            return jsonify({'status': 'error', 'message': '用户不存在'}), 404
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500

# 获取用户订单API（包括订单详情）
@app.route('/api/orders/user/<int:user_id>', methods=['GET'])
def get_user_orders(user_id):
    try:
        from backend.database.order_db import OrderDB
        from backend.database.order_detail_db import OrderDetailDB
        from backend.database.food_db import FoodDB
        import traceback
        
        print(f"收到获取用户订单请求，用户ID: {user_id}")
        
        order_db = OrderDB()
        order_detail_db = OrderDetailDB()
        food_db = FoodDB()
        
        # 获取用户的所有订单
        orders = order_db.get_orders_by_user_id(user_id)
        print(f"查询到{len(orders)}个订单")
        
        # 为每个订单添加订单详情和菜品信息
        result_orders = []
        for order in orders:
            order_dict = order.to_dict()
            
            # 获取订单详情
            order_details = order_detail_db.get_details_by_order_id(order.order_id)
            
            # 为每个详情添加菜品名称
            detailed_details = []
            for detail in order_details:
                detail_dict = detail.to_dict()
                # 获取菜品信息
                food = food_db.get_food_by_id(detail.food_id)
                if food:
                    detail_dict['food_name'] = food.food_name
                detailed_details.append(detail_dict)
            
            order_dict['order_details'] = detailed_details
            result_orders.append(order_dict)
        
        print(f"返回{len(result_orders)}个订单数据")
        return jsonify(result_orders)
    except Exception as e:
        print(f"获取用户订单错误: {str(e)}")
        print(f"错误堆栈: {traceback.format_exc()}")
        return jsonify({'status': 'error', 'message': str(e), 'error_type': type(e).__name__}), 500

# 支付订单API
@app.route('/api/orders/<int:order_id>/pay', methods=['PUT'])
def pay_order(order_id):
    try:
        from backend.database.order_db import OrderDB
        import traceback
        
        print(f"收到支付订单请求，订单ID: {order_id}")
        
        order_db = OrderDB()
        
        # 检查订单是否存在
        order = order_db.get_order_by_id(order_id)
        if not order:
            print(f"订单不存在: {order_id}")
            return jsonify({'status': 'error', 'message': '订单不存在'}), 404
        
        print(f"找到订单，当前状态: {order.order_status}")
        
        # 更新订单状态为已支付
        success = order_db.update_order_status(order_id, '已支付')
        
        if success:
            print(f"订单支付成功: {order_id}")
            return jsonify({'status': 'success', 'message': '订单支付成功'})
        else:
            print(f"订单支付失败: {order_id}")
            return jsonify({'status': 'error', 'message': '订单支付失败'}), 500
    except Exception as e:
        print(f"支付订单错误: {str(e)}")
        print(f"错误堆栈: {traceback.format_exc()}")
        return jsonify({'status': 'error', 'message': str(e), 'error_type': type(e).__name__}), 500

# 主页路由
@app.route('/')
def home():
    return "学生夜宵点餐系统后端服务已启动！"

if __name__ == '__main__':
    # 在开发环境中运行，生产环境请使用合适的WSGI服务器
    app.run(host='0.0.0.0', port=5000, debug=True)